#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
预算管理功能
"""

import sys
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QGridLayout, 
                             QLabel, QLineEdit, QPushButton, QTableWidget, 
                             QTableWidgetItem, QMessageBox, QHeaderView)
from PyQt5.QtCore import Qt
from database import Database


class BudgetWidget(QWidget):
    """预算管理面板"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_ui()
        self.load_budgets()
        
    def setup_ui(self):
        """设置界面"""
        layout = QVBoxLayout()
        
        # 预算设置区域
        budget_layout = QHBoxLayout()
        
        self.category_edit = QLineEdit()
        self.category_edit.setPlaceholderText("分类名称(支持一级或二级分类)")
        budget_layout.addWidget(self.category_edit)
        
        self.amount_edit = QLineEdit()
        self.amount_edit.setPlaceholderText("预算金额")
        budget_layout.addWidget(self.amount_edit)
        
        add_button = QPushButton("添加预算")
        add_button.clicked.connect(self.add_budget)
        budget_layout.addWidget(add_button)
        
        layout.addLayout(budget_layout)
        
        # 预算表格
        self.budget_table = QTableWidget()
        self.budget_table.setColumnCount(5)
        self.budget_table.setHorizontalHeaderLabels(["分类", "预算金额", "已支出", "剩余", "操作"])
        self.budget_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.budget_table.verticalHeader().setVisible(False)
        layout.addWidget(self.budget_table)
        
        self.setLayout(layout)
        
    def load_budgets(self):
        """加载预算数据"""
        db = Database()
        budgets = db.get_budgets()
        self.budget_table.setRowCount(len(budgets))
        
        for row, budget in enumerate(budgets):
            # 分类
            category_item = QTableWidgetItem(budget['category'])
            category_item.setFlags(category_item.flags() & ~Qt.ItemIsEditable)
            self.budget_table.setItem(row, 0, category_item)
            
            # 预算金额
            amount_item = QTableWidgetItem(f"{budget['amount']:.2f}")
            self.budget_table.setItem(row, 1, amount_item)
            
            # 已支出
            expense = db.get_monthly_expense(budget['category'])
            expense_item = QTableWidgetItem(f"{expense:.2f}")
            expense_item.setFlags(expense_item.flags() & ~Qt.ItemIsEditable)
            self.budget_table.setItem(row, 2, expense_item)
            
            # 剩余
            remaining = budget['amount'] - expense
            remaining_item = QTableWidgetItem(f"{remaining:.2f}")
            remaining_item.setFlags(remaining_item.flags() & ~Qt.ItemIsEditable)
            # 如果超支，设置为红色
            if remaining < 0:
                remaining_item.setForeground(Qt.red)
            self.budget_table.setItem(row, 3, remaining_item)
            
            # 操作按钮
            button_layout = QHBoxLayout()
            update_button = QPushButton("更新")
            update_button.clicked.connect(lambda _, r=row: self.update_budget(r))
            delete_button = QPushButton("删除")
            delete_button.clicked.connect(lambda _, r=row: self.delete_budget(r))
            
            button_widget = QWidget()
            button_layout.addWidget(update_button)
            button_layout.addWidget(delete_button)
            button_layout.setContentsMargins(0, 0, 0, 0)
            button_widget.setLayout(button_layout)
            self.budget_table.setCellWidget(row, 4, button_widget)
            
    def add_budget(self):
        """添加预算"""
        category = self.category_edit.text().strip()
        amount_text = self.amount_edit.text().strip()
        
        if not category or not amount_text:
            QMessageBox.warning(self, "输入错误", "分类和金额不能为空")
            return
            
        try:
            amount = float(amount_text)
        except ValueError:
            QMessageBox.warning(self, "输入错误", "金额必须是数字")
            return
            
        if amount <= 0:
            QMessageBox.warning(self, "输入错误", "金额必须大于0")
            return
            
        db = Database()
        db.add_budget(category, amount)
        self.category_edit.clear()
        self.amount_edit.clear()
        self.load_budgets()
        
    def update_budget(self, row):
        """更新预算"""
        category = self.budget_table.item(row, 0).text()
        amount_text = self.budget_table.item(row, 1).text()
        
        try:
            amount = float(amount_text)
        except ValueError:
            QMessageBox.warning(self, "输入错误", "金额必须是数字")
            return
            
        if amount <= 0:
            QMessageBox.warning(self, "输入错误", "金额必须大于0")
            return
            
        db = Database()
        db.update_budget(category, amount)
        self.load_budgets()
        
    def delete_budget(self, row):
        """删除预算"""
        category = self.budget_table.item(row, 0).text()
        reply = QMessageBox.question(self, "确认删除", f"确定要删除分类 '{category}' 的预算吗？", 
                                     QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            db = Database()
            db.delete_budget(category)
            self.load_budgets()